<?php
// $Id$

/**
 * Acctuser 封装来自 acct_user 数据表的记录及领域逻辑
 */
class Acctuser extends QDB_ActiveRecord_Abstract
{

	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
		// 指定该 ActiveRecord 要使用的行为插件
            'behaviors' => '',

		// 指定行为插件的配置
            'behaviors_settings' => array
		(
		# '插件名' => array('选项' => 设置),
		),

		// 用什么数据表保存对象
            'table_name' => 'acct_user',

		// 指定数据表记录字段与对象属性之间的映射关系
		// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
            'props' => array
		(
		// 主键应该是只读，确保领域对象的“不变量”
                'id' => array('readonly' => true),
                'addtime' => array('readonly' => true),

		/**
		 *  可以在此添加其他属性的设置
		 */
		# 'other_prop' => array('readonly' => true),

		/**
		 * 添加对象间的关联
		 */
		 'company'=>array('has_one'=>'company','on_delete'=>'skip','source_key'=>'company_id','target_id'=>'id'),

				),

		/**
		 * 允许使用 mass-assignment 方式赋值的属性
		 *
		 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
		 */
            'attr_accessible' => '',

		/**
		 * 拒绝使用 mass-assignment 方式赋值的属性
		 */
            'attr_protected' => 'id',

		/**
		 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
		 *
		 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
		 */
            'create_reject' => 'createtime',

		/**
		 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
		 */
            'update_reject' => '',

		/**
		 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
		 *
		 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
		 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
		 *
		 * 如果填充值为一个数组，则假定为 callback 方法。
		 */
            'create_autofill' => array
		(
		# 属性名 => 填充值
		   'addtime' => self::AUTOFILL_TIMESTAMP,
		),

		/**
		 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
		 *
		 * 填充值的指定规则同 create_autofill
		 */
            'update_autofill' => array
		(
		),

		/**
		 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
		 *
		 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
		 *
		 * 如果需要添加一个自定义验证，应该写成
		 *
		 * 'title' => array(
		 *        array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
		 * )
		 *
		 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
		 *
		 * static function checkTitle($title)
		 *
		 * 该方法返回 true 表示通过验证。
		 */
            'validations' => array
		(
		    
		),
		);
	}


	/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


	/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	
    function _after_create(){
        // if(empty($this->agent_acctname)){
        //     $this->team_tag = $this->id;
        // }else{
        //     $agentuser_obj = Acctuser::find('acctname = ?',$this->agent_acctname)->getOne();
        //     if($agentuser_obj->id()){
        //         $this->team_tag = $agentuser_obj->team_tag.','.$this->id;
        //     }else{
        //         $this->team_tag = $this->id;
        //     }
        // }
        $this->save();
    }

    //根据openid获取user_id
    static function getuseridbyopenid($openid){
    	if(empty($openid)){
    		return false;
    	}
    	$host = Helper_Common::getRequestHost();
    				$filename = Q::ini('app_config/ROOT_DIR').'/config/redis.yaml';
			$config = Helper_YAML::load($filename);
			$redis = new Redis();
			$redis->pconnect($config['host'],$config['port']);
	    if($redis->get("edulive:$host:openid_userid:".$openid)){
        	return $redis->get("edulive:$host:openid_userid:".$openid);
        }
        $user = acctuser::find(array("wechat_open_id"=>$openid))->getOne();
    	
    	$rd_ok = $redis->set("edulive:$host:openid_userid:".$openid,$user->id);
    	$redis->expire("edulive:$host:openid_userid:".$openid,86400);
    	return $user->id;
    }
    //根据openid获取user_info
    static function getuserinfobyopenid($openid){
    	$user = acctuser::find(array("wechat_open_id"=>$openid))->getOne();
    	return $user;
    }
    //获取用户信息
    static function getuserinfo($user_id){
    	$user = acctuser::find(array("id"=>$user_id))->asArray()->getOne();
    	return $user;
    	
    	/*$host = Helper_Common::getRequestHost();
    	$redis = new Redis();
	    $redis->connect('127.0.0.1',6379);
        if($redis->get("edulive:$host:user:".$user_id)){
        	return json_decode($redis->get("edulive:$host:user:".$user_id),true);
        }
    	$user = acctuser::find(array("id"=>$user_id))->asArray()->getOne();
    	$rd_ok = $redis->set("edulive:$host:user:".$user_id,json_encode($user));
    	$redis->expire("edulive:$host:user:".$user_id,86400);
        $redis->close();
    	return $user;*/
    }

    //创建更新微信用户信息
    static function followuser($acct_id,$openid,$unionid,$userinfo,$pid=0){
    	$user = acctuser::find(array("wechat_open_id"=>$openid))->getOne();
    	if(empty($user->id)){
    		$data = array(
    			"acct_id"=>$acct_id,
    			"username"=>$user->username?$user->username:$userinfo['nickName'],
    			"wechat_open_id"=>$openid,
    			"wechat_union_id"=>$unionid,
    			"nickname"=>$userinfo['nickName'],
    			"avatar_url"=>$userinfo['avatarUrl'],
			    "company_id"=>0,
			    "department"=>''
    		);
    		$teamtag=array();
    		//绑定上下级关系
    		if($pid!=0){
    			$data['parentid']=$pid;
    			$teamtag = acctuser::get_user_team($pid);
    			$user = new acctuser($data);
	    		$user->save();
	    		//更新team_tag
	    		array_push($teamtag, $user->id);
	    		$user->team_tag=implode(",", $teamtag);
	    		$user->save();
    		}else{
    			$user = new acctuser($data);
	    		$user->save();
	    		$user->team_tag=$user->id;
	    		$user->save();
    		}
    	}else{
    		$user->acct_id = $acct_id;
	    	$user->username = $user->username?$user->username:$userinfo['nickName'];
	    	$user->wechat_open_id = $openid;
	    	$user->wechat_union_id = $unionid;
	    	$user->nickname = $userinfo['nickName'];
	    	$user->avatar_url = $userinfo['avatarUrl'];
	    	$user->save(0,'update');
    	}
    	return $user->id;
    }

    //获取teamtag
    static function get_user_team($pid){
    	$arr=[$pid];
    	//第一级
    	$puser = acctuser::find("id = ".$pid)->setColumns('parentid')->getOne();
    	if($puser->parentid>0){
    		//第二级
    		$arr=[$puser->parentid,$pid];
    		$p2user = acctuser::find("id = ".$puser->parentid)->setColumns('parentid')->getOne();
    		if($p2user->parentid>0){
    			//第三级
    			$arr=[$p2user->parentid,$puser->parentid,$pid];
    		}
    	}
    	return $arr;
    }
    //修改上级
    static function editparent($user_id,$parentid){
    	$user = Acctuser::find("id =?",$user_id)->getOne();
    	if(!$user->id()){
    		return false;
    	}
    	if($parentid!=0){
    		$parent = Acctuser::find("id =?",$parentid)->getOne();
    		if(!$parent->id()){
    			return false;
    		}
    	}
    	$acct_id = $user->acct_id;
    	$now_parentid = $user->parentid;
    	//不许修改
    	if($now_parentid==$parentid){
    		return false;
    	}
    	//本人
    	$user->parentid = $parentid;
		if($parentid==0){
			$user->team_tag = $user_id;
			$user->save();
		}else{
			$array = explode(',',$parent->team_tag);
			if(count($array)>3){
				unset($array[0]);
			}
			array_push($array, $user_id);
			$team_tag = implode(',', $array);
			$user->team_tag = $team_tag;
			$user->save();
		}

    	
    	$sql = "SELECT id,team_tag,parentid FROM acct_user where acct_id = $acct_id AND FIND_IN_SET($user_id,acct_user.team_tag)";

    	$user_list = QDB::getConn()->execute($sql)->fetchAll();
    	for ($i=0; $i < count($user_list); $i++) { 
    		//关系户
    		if($user_list[$i]['id']!=$user_id){
    			$user = Acctuser::find("id = ?",$user_list[$i]['id'])->getOne();
    			if($parentid==0){
    				$array = explode(',',$user->team_tag);
    				$array = array_reverse($array);
    				$key = array_search($now_parentid,$array);
    				array_splice($array,$key);
    				$array = array_reverse($array);
    				$team_tag = implode(',', $array);
    				$user->team_tag = $team_tag;
    				$user->save();
    			}else{
    				$array = explode(',',$user->team_tag);
    				$key = array_search($now_parentid, $array);
    				$parent_array = explode(',',$parent->team_tag);
    				if($key==0){
    					$array[0]=$parentid;
    				}elseif ($key == 1) {
    					array_reverse($parent_array);
    					if(count($parent_array)>=2){
    						$array[0]=$parent_array[0];
    						$array[1]=$parent_array[1];
    					}else{
    						$array[1]=$parent_array[0];
    						unset($array[0]);
    					}
    					
    				}elseif($key==2){
    					array_reverse($parent_array);
    					if(count($parent_array)>=3){
    						$array[0]=$parent_array[0];
    						$array[1]=$parent_array[1];
    						$array[2]=$parent_array[2];

    					}elseif(count($parent_array)==2){
    						$array[0]=$parent_array[0];
    						$array[1]=$parent_array[1];
    					}else{
    						$array[1]=$parent_array[0];
    						unset($array[0]);
    					}
    				}

					$team_tag = implode(',', $array);
    				$user->team_tag = $team_tag;
    				$user->save();
    			}
    		}
    		
    	}
    	return true;
    	
    }

    //分销中心

    static function getfenxiao($user_id){
    	//佣金条数
    	$commission_count = fxcommission::find('object_uid = '.$user_id)->getCount();
    	$list['commission_count'] = $commission_count;
    	//提现条数
    	$withdraw_count = fxwithdraw::find('user_id = '.$user_id)->getCount();
    	$list['withdraw_count'] = $withdraw_count;
    	//下线人数
    	$list['xx_count'] = acctuser::getteamnum($user_id);
    	return $list;
    }
    /**
	 * 获取分销下线用户数量
	 */
    static function getteamnum($user_id){
    	$sql = "SELECT id,team_tag FROM acct_user WHERE FIND_IN_SET($user_id,team_tag) AND id != $user_id;";
    	$user_info = acctuser::getuserinfo($user_id);
    	$acct_id = $user_info['acct_id'];
    	$fxset = fxset::getfxset($acct_id);

    	$user_list = QDB::getConn()->execute($sql)->fetchAll();
    	$xx_count=0;
    	//分离下线层级
    	for ($i=0; $i < count($user_list); $i++) { 
    		//截取team_tag
    		$str = $user_list[$i]['team_tag'];
			$t = explode($user_id,$str);
			//获取下级
			if($t[1]){
				$team_arr = explode(',', trim($t[1],','));
				//判断层级
				if(count($team_arr)<=intval($fxset->level)){
					$xx_count++;
				}
				
			}
		}
		return $xx_count;
    }
    /**
	 * 获取分销下线用户
	 */
    static function getmyteam($user_id){
    	$sql = "SELECT id,team_tag,parentid,nickname,avatar_url,total_consume,commission,used_commission,fx_grade,addtime FROM acct_user WHERE FIND_IN_SET($user_id,team_tag) AND id != $user_id;";
    	$list = QDB::getConn()->execute($sql)->fetchAll();
    	$first = array();
    	$second = array();
    	$third = array();

    	$user_info = acctuser::getuserinfo($user_id);
    	$acct_id = $user_info['acct_id'];
    	$fxset = fxset::getfxset($acct_id);
    	//分离下线层级
    	for ($i=0; $i < count($list); $i++) { 
    		//截取team_tag
    		$str = $list[$i]['team_tag'];
			$t = explode($user_id,$str);
			//获取下级
			if($t[1]){
				$team_arr = explode(',', trim($t[1],','));
				//格式化时间
    			$list[$i]['addtime']=date('Y-m-d',$list[$i]['addtime']);
    			$list[$i]['total_commission'] = $list[$i]['commission']+$list[$i]['used_commission'];
    			$list[$i]['team_num'] = acctuser::getteamnum($list[$i]['id']);
    			//第一级下线
	    		if(count($team_arr)==1 && count($team_arr)<=intval($fxset->level)){
	    			array_push($first, $list[$i]);
	    		}elseif(count($team_arr)==2 && count($team_arr)<=intval($fxset->level)){
	    			//第二级下线
	    			array_push($second, $list[$i]);
	    		}elseif(count($team_arr)==3 && count($team_arr)<=intval($fxset->level)){
	    			//第三级下线
	    			array_push($third, $list[$i]);
	    		}
			}

    	}
    	$res['first'] = $first;
    	$res['second'] = $second;
    	$res['third'] = $third;
    	return $res;
    }

    /**
	 * 获取父级用户
	 */
    static function getmyparentids($user_id){
    	$userinfo = acctuser::find("id = ?",$user_id)->setColumns('id,team_tag')->getOne();
    	$str = $userinfo->team_tag;
		$t = explode($user_id,$str);
		//获取上级
		if(!empty($t[0])){
			$team_arr = explode(',', trim($t[0],','));
			return $team_arr;
		}
		return false;

    }
    //用户vip等级
    static function getuserviplevel($user_id){
    	$user = Acctuser::getuserinfo($user_id);
    	if($user['viplevel_id']>0 && $user['due_time']>time()){
    		return $user['viplevel_id'];
    	}else{
    		return 0;
    	}
    }


	/**
	 * 检查用户名规则
	 * @param string $user
	 */
	public static function checkUserName($userName)
	{
		if(!QValidator::validate_between(strlen($userName), 4, 12))
		{
			return -1;
		}else if(QValidator::validate_is_digits($userName)){
			return -2;
		}else {
			return 0;
		}
	}

	public static function getbdlist() {
	    $data = array(''=>'请选择',0=>'平台');
	    $apply_listsql =  'select id,acctname,realname from acct_user where is_bd = 1 and bd_status = 1';
	    $apply_list =   QDB::getConn()->execute($apply_listsql)->fetchAll();
	    if(count($apply_list)){
	        foreach ($apply_list as $v){
	            $data[$v['id']]  = $v['realname'].'('.$v['acctname'].')';
	        }
	    }
	    return $data;
	}
	public static function getbdlisthuabo() {
	    $data = array(''=>'请选择');
	    $apply_listsql =  'select id,acctname,realname from acct_user where is_bd = 1 and bd_status = 0';
	    $apply_list =   QDB::getConn()->execute($apply_listsql)->fetchAll();
	    if(count($apply_list)){
	        foreach ($apply_list as $v){
	            $data[$v['id']]  = $v['realname'].'('.$v['acctname'].')';
	        }
	    }
	    return $data;
	}
	
	public static function getlevelname($level){
	    $name = '经理';
	    $level = level::find('id = ?',$level)->getOne();
	    if($level->id()){
	        $name = $level->name;
	    }
	    return $name;
	}
	
	public static function getlevellist(){
	   
	    $level = level::find()->asArray()->order('id asc')->getAll();
	    $result = Helper_Array::toHashmap($level, 'id','name');
	    return $result;
	}
	
	static function getdainumbyuid($uid,$nowuser){
	    if(!is_array($nowuser)) 
	     $nowuser = $nowuser->toArray();
	
	    $uid = "$uid";
	 
	    $teamtag = $nowuser['team_tag'];
	   
	    if(strpos($teamtag,$uid) === false){
	        return false;
	    }else{
	        
	        $tag_array = explode(',', $teamtag);
	       
	        if(count($tag_array) == 1){
	            return 0;
	        }else{
	            $key_upuid = 0;
	            $daishunum = 0;
	            foreach ($tag_array as $k=>$v){
	                if($v == $uid){
	                    $key_upuid = $k;
	                }
	            } 
	            $daishunum = count($tag_array) - 1 - $key_upuid ;
	            return $daishunum;
	        }
	    }
	}
	/**
	 * 推荐奖励
	 * @param unknown $grade
	 */
	static function getrecrewardbygrade($grade){
	    if($grade > 8 ||$grade <1){
	        return 0;
	    }else{
    	    $array = array(
    	        1=>21,
    	        2=>7,
    	        3=>7,
    	        4=>3,
    	        5=>3,
    	        6=>3,
    	        7=>3,
    	        8=>3,
    	    );
    	    return $array[$grade];
	    }
	}
	/**
	 * 团队级差奖励
	 * @param unknown $upuser
	 *
	 */
	static function getrewardbalancebygrade($upuser){
	    $maxjichalevelkey = 'maxjichalevel'.$upuser->acctname;
        if(empty($_SESSION[$maxjichalevelkey] ))$_SESSION[$maxjichalevelkey] = 1;
	    if(!$upuser->id()){
	        return 0;
	    }else{
	        
	        $reardmoney = 0;
	        $reward_array = array(
	            1=>0,
	            2=>7.5,
	            3=>10,
	            4=>12.5,
	            5=>15
	        );
	       
	        $level = $upuser->level;
	    
	        if($level > $_SESSION[$maxjichalevelkey]){
	            $reardmoney = $reward_array[$level] - $reward_array[$_SESSION[$maxjichalevelkey]];
	            $_SESSION[$maxjichalevelkey] = $level;
	        }
	        return $reardmoney;
	    }
	}
	/**
	 * 加积分 
	 * @param unknown $nowuser
	 * @param unknown $rewarduser
	 * @param unknown $level
	 */
	static function pointadd($nowuser,$rewarduser,$level,$type,$balance,$remark){
	    $data = array(
	        'reward_acctname'=>$rewarduser->acctname,
	        'reward_realname'=>$rewarduser->realname,
	        'acctname'=>$nowuser->acctname,
	        'realname'=>$nowuser->realname,
	        'level'=>$level,
	        'type'=>$type,
	        'balance'=>$balance,
	        'remark'=>$remark,
	    );
	    $o = new pointlog($data);
	    $o->save();
	    
	}
	/**
	 * 判断用户升级
	 */
	static function checkuplevel($upuser){
	    
	    $nowlevel = $upuser->level;
	    $uplevel_after = 0;
	    if($upuser->rec_total >= 5 && $upuser->team_total >= 20){
	        $uplevel_after = 1;
	    }
	    if($upuser->rec_total >= 20 && $upuser->team_total >= 100){
	        $uplevel_after = 2;
	    }
	    if($upuser->rec_total >= 35 && $upuser->team_total >= 500){
	        $uplevel_after = 3;
	    }
	    if($upuser->rec_total >= 50 && $upuser->team_total >= 1500){
	        $uplevel_after = 4;
	    }
	  
	   if($uplevel_after > $nowlevel){
	       $upuser->level = $uplevel_after;
	       $upuser->save();
	   }else{
	       return ;
	   }
	}
	
	/**
	 * 用户激活时候计算所有上级的奖励以及升级
	 */
	static function rewardandlevelup($user,$i){
	    
	    
	    //递归循环    
	    $agent_acctname = $user->agent_acctname;
	     
	    if($agent_acctname){
	        $upuser = self::find('acctname = ?',$agent_acctname)->getone();
	        if($upuser->id() ){
	           
    	            $i += 1;	            
    	            if($i == 1){//增加直推人数
    	                $upuser->rec_total  = $upuser->rec_total +1;
    	                $upuser->save();
    	            }
    	          
    	            //增加团队人数
    	            $upuser->team_total  = $upuser->team_total +1;
    	            $upuser->save();
    	            
    	            //用户升级检测
    	            self::checkuplevel($upuser);
    	            if($upuser->is_active == 1){//用户只有激活了才享受奖励
        	            //获取推荐奖励金额---加推荐奖励
        	            $rec_rewardmoney = self::getrecrewardbygrade($i);
        	            $upuser->balance  = $upuser->balance +$rec_rewardmoney;
        	            $upuser->save();
        	         //   echo $rec_rewardmoney;
        	            self::pointadd($user, $upuser, $i, 0, $rec_rewardmoney, '第'.$i.'代推荐奖励'.$rec_rewardmoney);
        	            
        	            //获取团队奖励金额---加团队奖励积分--这里是级差奖励
        	            $rewardmony = self::getrewardbalancebygrade($upuser);
        	       //  echo $rewardmony;
        	            if($rewardmony >0){
        	                $upuser->balance  = $upuser->balance +$rewardmony;
        	                $upuser->save();
        	                self::pointadd($user, $upuser, $i, 1, $rewardmony, '第'.$i.'代团队级差奖'.$rewardmony);
        	        }
	            }
	            //迭代当前用户
	            $user = $upuser;
	            self::rewardandlevelup($user,$i);
	           }else{
	               return ;
	           }
	        }else{
	            return ;
	        }
      
	}
	//获取个人分享二维码
	 static function getQrcode($acct_id, $user_id,$path=null,$scene=null)
    {
    	$user = acctuser::find("id = ?",$user_id)->getOne();
    	if($user->id()){
    		if($user->distrib_pic && !$path){
    			return [
	                'code' => 0,
	                'qr_img' => $user->distrib_pic,
	            ];
    		}
    		
    	}
    	$conf = acct::find("id = ".$acct_id)->getOne();
        $access_token = Helper_common::wx_get_token($conf->app_id,$conf->app_secret);
        
        if (!$access_token) {
            return [
                'code' => 1,
                'msg' => $access_token->errMsg,
            ];
        }
        $api = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
        $data = json_encode([
            'scene' => $scene?$scene:"mid=$user_id",
            'page' => $path?$path:'pages/index/index',
            'width' => 246,
        ]);

        $response = Helper_common::send_post($api, $data);

        $url = Helper_Common::getJiqunHost();

        if (!is_array($response)) {
            //返回图片
            if($path){
            	$user->distrib_pic=$url.acctuser::saveTempImageByContent($response);
	        	$user->save();
	            return [
	                'code' => 0,
	                'qr_img' => $user->distrib_pic,
	            ];
            }else{
            	 return [
	                'code' => 0,
	                'qr_img' => $url.acctuser::saveTempImageByContent($response),
	            ];
            }
        	
        } else {
            //返回文字
            $res = json_decode($response, true);
            return [
                'code' => 1,
                'msg' => $res['errmsg'],
            ];
        }
    }

    //保存图片内容到临时文件
    static function saveTempImageByContent($content)
    {
        $save_path = 'uploadfiles/qrcode/' . md5(base64_encode($content)) . '.jpg';
        $fp = fopen($save_path, 'w');
     //    $base64   = base64_encode($content);
    	// return ('data:' . $mime . ';base64,' . $base64);
        fwrite($fp, $content);
        fclose($fp);
        return $save_path;
    }

    //获取网络图片到临时目录
    static function saveTempImage($url)
    {

        // $ch = curl_init($url);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        // $img = curl_exec($ch);
        // curl_close($ch);
        $img = Helper_Common::get_data($url);
        if(!is_dir('uploadfiles/user_head/')){
        	mkdir('uploadfiles/user_head/');
        }
        $save_path = 'uploadfiles/user_head/' . md5(base64_encode($img)) . '.jpg';
        $fp = fopen($save_path, 'w');
        fwrite($fp, $img);
        fclose($fp);
        return $save_path;
    }

}

